from django.views.decorators.csrf import csrf_protect
from django.db import IntegrityError
from django.shortcuts import render, redirect
from nse_webapp.forms import SignUpForm, SignInForm
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout

@csrf_protect
def signup(request):
    c = {}
    s_form = SignUpForm(request.POST or None)
    c['sform'] = s_form
    c['form_title'] = "New exchanger? Sign Up!"
    c['button_label'] = 'Sign up to exchange!'
    if request.method == 'POST':
        if s_form.is_valid():
            lastname = s_form.cleaned_data['lastname']
            firstname = s_form.cleaned_data['firstname']
            email = s_form.cleaned_data['email']
            password = s_form.cleaned_data['password']
            try:
                user = User.objects.create_user(email, email, password)
            except IntegrityError:
                s_form.errors['email'] = ['Non unique login/email',]
                return render(request, 'sign_up.html', c)
            user.first_name = firstname
            user.last_name = lastname
            user.save()
            c['user'] = user
            user = authenticate(username=email, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return redirect("/") 

    return render(request, 'sign_up.html', c)

@csrf_protect
def signin(request):    
    c = {}
    s_form = SignInForm(request.POST or None)
    c['sform'] = s_form
    c['form_title'] = "Already registered? Sign In!"
    c['button_label'] = 'Sign in to exchange!'
    
    if request.method == 'POST':
        if s_form.is_valid():
            email = s_form.cleaned_data['login']
            password = s_form.cleaned_data['password']
            user = authenticate(username=email, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return redirect("/") 

    return render(request, 'sign_up.html', c)

def signout(request):
    logout(request)
    return redirect("/") 